package correspondence;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class Demo3 {
    public static void main(String[] args) {
        Printer3 p = new Printer3();
        new Thread(() -> {
            while (true) {
                try {
                    p.print1();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            }).start();
        new Thread(() -> {
            while (true) {
                try {
                    p.print2();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();
        new Thread(() -> {
            while (true) {
                try {
                    p.print3();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();
    }
}
class Printer3{
    ReentrantLock lock = new ReentrantLock();

    Condition c1 = lock.newCondition();
    Condition c2 = lock.newCondition();
    Condition c3 = lock.newCondition();

    int flag = 1;

    public void print1() throws InterruptedException {
        lock.lock();
        if (flag != 1) {
            //线程1等待，c1第一次执行await，所以c1绑定线程1
            c1.await();
        }
        System.out.print("周");
        System.out.print("新");
        System.out.print("琦");
        System.out.println();
        flag = 2;
        c2.signal();
        lock.unlock();
    }
    public void print2() throws InterruptedException {
        lock.lock();
        if (flag != 2) {
            c2.await();
        }
        System.out.print("麦");
        System.out.print("啊");
        System.out.print("迷");
        System.out.println();
        flag = 3;
        c3.signal();
        lock.unlock();
    }
    public void print3() throws InterruptedException {
        lock.lock();
        if (flag != 3) {
            c3.await();
        }
        System.out.print("c");
        System.out.print("s");
        System.out.print("go");
        System.out.println();
        flag = 1;
        c1.signal();
        lock.unlock();

    }

}
